package com.ph.realm;

import com.ph.feign.GroupFeign;
import com.ph.config.PhonePasswordToken;
import com.ph.pojo.User;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class LoginRealm extends AuthorizingRealm {

    @Autowired
    private GroupFeign groupFeign;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof PhonePasswordToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        PhonePasswordToken token1 = (PhonePasswordToken) token;
        if (token1.getPhone() == null){
            throw new AuthenticationException("手机号不能为空");
        }
        if (token1.getPassword() == null){
            throw new AuthenticationException("密码不能为空");
        }
        User user = groupFeign.userFindByPhone(token1.getPhone()).getData();
        if (user == null){
            throw new AuthenticationException("用户不存在");
        }
        if (user.getStatus().equals("离职")){
            throw new AuthenticationException("该用户已离职");
        }
        return new SimpleAuthenticationInfo(user.getId(), user.getPassword(),getName());
    }
}
